<template>
  <el-row :gutter="10" style="width: 100%;height: 100%;">

    <transition name="el-zoom-in-center">
      <el-col :span="drawer?6:1" style="height: 100%">
        <el-row style="width: 100%;height: 100%;">
          <el-col :span="21" style="height: 100%" v-show="drawer">
            <work-book-config v-if="activeMode == 2"
                              :work-book="workBook"
                              :data-source="dataSource"
                              @handleSave="handleSave">
            </work-book-config>
            <work-book-data-config v-else :work-book="workBook" :data-source="dataSource"></work-book-data-config>
          </el-col>
          <el-col :span="drawer?3:24">
            <el-menu
              default-active="2"
              :collapse="true"
              :background-color="share.darkMode?'#29324A':'#ffffff'"
              style="width: 64px;border-right: none"
            >
              <el-menu-item @click="drawer=!drawer">
                <i :class="drawer?'el-icon-d-arrow-left':'el-icon-d-arrow-right'" ></i>
                <template #title>
                  折叠/展开工具栏
                </template>
              </el-menu-item>
              <el-menu-item index="2" @click="activeMode=2" >
                <i class="el-icon-setting" ></i>
                <template #title>图表配置</template>
              </el-menu-item>
              <el-menu-item index="3" @click="activeMode=3">
                <i class="el-icon-s-grid" ></i>
                <template #title>数据设置</template>
              </el-menu-item>
            </el-menu>
          </el-col>
        </el-row>

      </el-col>
    </transition>


    <!--    <transition name="el-zoom-in-center">-->
    <!--      <el-col :span="drawer?8:0" style="height: 100%" v-show="drawer">-->
    <!--        <el-row style="width: 100%;height: 100%;">-->
    <!--          <el-col :span="10" style="height: 100%">-->
    <!--            <work-book-config :work-book="workBook" :data-source="dataSource"-->
    <!--                              @handleSave="handleSave"></work-book-config>-->
    <!--          </el-col>-->
    <!--          <el-col :span="14" style="height: 100%">-->
    <!--            <work-book-data-config :work-book="workBook" :data-source="dataSource"></work-book-data-config>-->
    <!--          </el-col>-->
    <!--        </el-row>-->
    <!--      </el-col>-->
    <!--    </transition>-->

    <el-col :span="drawer?18:23" style="height: 100%">
      <el-row style="height: 100%">
        <preview ref="workBookPreview" :workBook="workBook"></preview>
      </el-row>
    </el-col>
  </el-row>

</template>

<script>
import WorkBookConfig from "@/components/workbook/WorkBookConfig";
import WorkBookDataConfig from "@/components/workbook/WorkBookDataConfig";
import {getWorkBook, loadData, parseToObj, saveWorkBook} from "@/api/workBook";
import preview from "@/views/WorkBook/preview";
import {updateTask} from "@/utils/tasknotify";
import {dateFormat} from "@/filter";
import {getDataSource} from "@/api/dataSource";
import {onMounted, reactive, ref, toRefs} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {onBeforeRouteUpdate, useRoute, useRouter} from "vue-router";
import {store} from "@/components/chart/common/store";

export default {
  name: "editWorkBook",
  components: {
    WorkBookConfig,
    preview,
    WorkBookDataConfig
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const defaultWorkBook = {
      rows: [],
      columns: [],
      //筛选
      filters: [],
      //分页
      limit: {
        take: 10
      },
      //外链参数
      urlParams: [],
      //自动更新，0表示不更新，单位分钟
      autoUpdate: 0,
      //同环比计算标识
      isYoy: false,
      yoyType: 'year',
      //二级维度
      subDimension: []
    };
    const workBook = ref(defaultWorkBook);
    const dataSource = ref({});
    const state = reactive({
      data: [],
      activeMode: 2
    })
    const loadWorkBook = async (workBookId) => {
      let workBookResp = await getWorkBook(workBookId);
      if (workBookResp.data) {
        dataSource.value = await getDataSource(workBookResp.data.dataSourceId);
        workBook.value = parseToObj(workBookResp.data)
      } else {
        ElMessage.error("没有找到对应的图表，请检查参数是否正确：" + workBookId)
      }
    }
    const workBookPreview = ref(null)
    //重新加载数据并刷新图表
    const reload = () => {
      if (dataSource.value.id) {
        //加载数据
        loadData(workBook.value, dataSource.value).then(data => {
          state.data = data
          //刷新图表
          workBookPreview.value.refreshChart(workBook.value, data)
        });
      }
    }
    //只刷新图表配置
    const review = () => {
      workBookPreview.value.refreshChart(workBook.value, state.data)
    }

    onMounted(() => {
      if (route.query.id) {
        loadWorkBook(route.query.id);
      }
    })

    onBeforeRouteUpdate(newVal => {
      if (newVal.query.id) {
        loadWorkBook(newVal.query.id)
      } else {
        dataSource.value = {};
        workBook.value = defaultWorkBook;
      }
    });

    //保存当前图表
    const handleSave = () => {
      //没有选择数据源则动作取消
      if (!dataSource.value.id || (workBook.value.rows.length === 0 && workBook.value.columns.length === 0 && !workBook.value.colorMark.annexField)) {
        ElMessage.error("当前图表没有任何内容，不可保存!")
        return false;
      }
      let task = {}
      ElMessageBox.prompt('请输入图表名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: workBook.value.name
      }).then(({value}) => {
          workBook.value.name = value || `未命名图表${dateFormat(new Date(), "yyyyMMDDhhmmss")}`;
          workBook.value.dataSourceId = dataSource.value.id;
          task = updateTask({
            msg: "保存图表[" + workBook.value.name + "]"
          });
          return saveWorkBook(workBook.value).then(resp => {
            task.status = "success";
            task.msg = "【完成】" + task.msg;
            updateTask(task)
            workBook.value.id = resp.data.id
            ElMessageBox.confirm('保存成功，是否进入展示页查看？', '提示', {
              type: 'success',
              showCancelButton: true,
              confirmButtonText: '立即预览',
              cancelButtonText: '不用了谢谢'
            }).then(() => {
              const path = router.resolve({name: 'workBookView', query: {id: workBook.value.id}})
              window.open(path.href, '_blank')
            })
          }).catch(error => {
            task.status = "error";
            task.msg = "【出错】" + task.msg + ":" + error;
            updateTask(task)
          })
        }
      )
    }

    return {
      workBook, dataSource, handleSave, workBookPreview, review, reload, ...toRefs(state)
    }
  },
  data() {
    return {
      share: store,
      drawer: true,
      keyword: '',
      provinceList: [],
      subscribes: []
    };
  },
  computed: {
    //监听哪些字段变化需要重新加载图表及数据
    workReloadWatch() {
      return {
        filters: this.workBook.filters,
        urlParams: this.workBook.urlParams,
        subDimension: this.workBook.subDimension,
        columns: this.workBook.columns,
        rows: this.workBook.rows,
        limit: this.workBook.limit,
        isYoy: this.workBook.isYoy,
        yoyType: this.workBook.yoyType
      }
    }
  },
  emits: ['handleEditDataSource'],
  watch: {
    workReloadWatch: {
      handler() {
        this.reload()
      },
      deep: true
    },
    'workBook.chartConfig': {
      deep: true,
      handler() {
        this.review()
      }
    }
  }
}
</script>

<style scoped>

</style>
